<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2023/12/4
 * Time: 10:34
 */

namespace app\zyhsapi\controller\v1;

use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrMessage;
use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\lib\OrdersLib;
use app\zyhsapi\model\ZyhsAstrTasks;
use app\zyhsapi\model\ZyhsOrders;
use app\zyhsapi\model\ZyhsQuestionUserView;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserAddQuestion;
use app\zyhsapi\model\ZyhsUserQuestion;
use think\Log;

class Orders extends ZyhsAuth
{
    /**
     * 列表
     * @return mixed
     * @throws \Exception
     */
    public function payUnlock()
    {
        $param['order_type'] = input('param.order_type/d', 101);
        $param['trade_type'] = input('param.trade_type/d', 4);
        $param['gid'] = input('param.gid/d', 0);
        $param['param'] = input('param.param', '');
        $paramInfo = json_decode($param['param'], true);
        $param['data_id'] = $paramInfo['data_id'] ?? '';
        //获取商品信息
        $goodsConfig = config('zyhsgoods')['qa_goods'];
        $goods = $goodsConfig[$param['gid']] ?? [];
        if (!$goods)
        {
            return show(config('code.error'), '未知的商品');
        }
        //验证准币余额
        $balance = (new ZyhsUserAccount())->getCoinNum($this->user['id']);
        if ($balance < $goods['now_prize'])
        {
            return show(410, '准币不足');
        }
        $questionModel = new ZyhsUserQuestion();
        // 根据gids区分是问题,追问还是蹭看
        $questionType = $questionModel->getQuestionType($param['gid']);
        // 验证问题
        $questionInfo = $this->checkQuestion($param, $questionType);
        $order_type_des = OrdersLib::createOrderId($param['order_type']);
        $param['out_trade_no'] = $order_type_des['order_id'];
        $price = $goods['now_prize'] / 10; //计算商品价格
        //扣除准币
        $res = OrdersLib::UpdateCoin($param['out_trade_no'], $param['order_type'], $price, $this->user['id'], 2, 4, '', $param['gid']);
        if ($res === true)
        {
            // 处理订单和问题
            (new ZyhsOrders())->SaveData([
                'status' => $questionType['type'] === 1 ? 4 : 1,
                'order_type' => $param['order_type'],
                'uid' => $this->user['id'],
                'gid' => $param['gid'],
                'order_id' => $param['out_trade_no'],
                'trade_type' => $param['trade_type'],
                'total_amount' => $price,
                'create_time' => $this->request->time(),
                'pay_time' => $this->request->time(),
            ]);
            $this->dealQuestion($param, $questionType, $questionInfo, $goods);
            return show(config('code.success'), 'Success.', ['order_id' => $param['out_trade_no']]);
        }
        return show(config('code.error'), '服务异常，请稍后重试～');
    }

    /**
     * 检测问题
     * @param $param
     * @param $questionType
     * @return array|mixed|\think\response\Json
     * @throws ApiException
     */
    private function checkQuestion(&$param, $questionType)
    {
        if (!$param['trade_type'])
        {
            throw new ApiException('请求异常');
        }
        if (!$param['order_type'])
        {
            throw new ApiException('请求异常');
        }
        $questionModel = new ZyhsUserQuestion();
        $taskModel = new ZyhsAstrTasks();
        switch ($questionType['type'])
        {
            case 1://蹭看
                $questionInfo = $taskModel->getInfoById($param['data_id']);
                if (!$questionInfo)
                {
                    throw new ApiException('请求异常，问题不存在');
                }
                //是否已蹭看
                $res = (new ZyhsQuestionUserView())->getQuestionUserIsView($this->user['id'], (int)$param['data_id']);
                if ($res)
                {
                    throw new ApiException('不能重复蹭看');
                }
                break;
            case 2://追问
                //获取追问缓存
                $dataId = (int)$param['data_id'];
                $addQuestion = (new ZyhsUserAddQuestion())->getTmpAddQuestionData($dataId);//任务ID
                if (!$addQuestion)
                {
                    throw new ApiException('请求异常，问题不存在');
                }
                $param['question'] = $addQuestion['content'];
                $questionInfo = $taskModel->getInfoById($dataId);
                if (!$questionInfo || $questionInfo['uid'] != $this->user['id'])
                {
                    throw new ApiException('请求异常，问题不存在');
                }
                //待追问的任务才可追问
                if ($questionInfo['status'] != 3)
                {
                    throw new ApiException('不可追问');
                }
                if ($questionType['sec'] !== (int)$questionInfo['question_type'])
                {
                    throw new ApiException('请求异常');
                }
                // 删除追问缓存
                (new ZyhsUserAddQuestion())->rmTmpAddQuestionData($dataId);
                break;
            case 3://问答 问答订单需要验证问题信息,非待下单问题不能再次下单
                $questionInfo = $questionModel->getTmpQuestionDataCache($param['data_id']);//缓存key
                if (!$questionInfo || $questionInfo['uid'] != $this->user['id'])
                {
                    throw new ApiException('请求异常，问题不存在');
                }
                // 删除问题缓存
                $questionModel->delTmpQuestionDataCache($param['data_id']);
                break;
            default:
                throw new ApiException('请求异常，问题不存在');
        }
        return $questionInfo;
    }

    /**
     * 处理问题
     * @param $param
     * @param $questionType
     * @param $questionInfo
     * @param $goods
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function dealQuestion($param, $questionType, $questionInfo, $goods)
    {
        try
        {
            $questionModel = new ZyhsUserQuestion();
            $taskModel = new ZyhsAstrTasks();
            switch ($questionType['type'])
            {
                case 1://蹭看
                    (new ZyhsQuestionUserView())->SaveData([
                        'uid' => $this->user['id'],
                        'is_hide' => 0,
                        'task_id' => $param['data_id'],//问题任务ID
                        'order_num' => $param['out_trade_no'],
                        'good_amount' => $goods['now_prize'],   // 实际支付价格（准币）
                        'new_answer' => 0,
                        'status' => 1,
                        'create_time' => $this->request->time(),
                    ]);
                    break;
                case 2://追问
                    $addQuestionId = (new ZyhsUserAddQuestion())->SaveData($param['data_id'], [
                        'uid' => $this->user['id'],
                        'activity_discount' => 1,
                        'task_id' => $param['data_id'],//问题任务ID
                        'status' => 2,
                        'order_num' => $param['out_trade_no'],
                        'good_amount' => $goods['now_prize'],   // 实际支付价格（准币）
                        'question' => $param['question'],
                        'create_time' => $this->request->time(),
                        'pay_time' => $this->request->time(),
                    ]);
                    //任务更新为追问待解答
                    $taskModel->UpdateData($param['data_id'], $questionInfo['astr_id'], ['status' => 5, 'update_time' => $this->request->time()]);
                    // 给占星师发送短信
                    $hour = (int)(date('H'));
                    if ($hour >= 10 && $hour < 20)
                    {   // 白天
                        $msgContent = "你的任务{$param['data_id']}有新的追问，请在3小时内给出回复，超时将受到惩罚。";
                        $timeStr = '3小时内给出';
                    } else
                    {   // 晚上
                        $timeStr = $hour >= 20 ? '次日11点前' : '11点前';
                        $msgContent = "你的任务{$param['data_id']}有新的追问，请在{$timeStr}回复，超时将受到惩罚。";
                    }
                    $tel = (new ZlcrAstr())->getInfoById($questionInfo['astr_id'], ['tel']);
                    Util::sendHySms([$tel['tel']], '', 131493, ['task_id' => $param['data_id'], 'time' => $timeStr]);

                    // 发送占星师站内信
                    (new ZlcrAstrMessage())->add($questionInfo['astr_id'], [
                        'status' => 0,
                        'is_read' => 0,
                        'astr_id' => $questionInfo['astr_id'],
                        'type' => 0, // 占星师违规消息
                        'title' => '追问提示',
                        'content' => $msgContent,
                        'target' => '',
                        'link' => '',
                        'create_time' => $this->request->time(),
                    ]);
                    // if ($hour >= 10 && $hour < 20) 不发送
                    // {   // 白天   追问1小时是否回复检测 未回复发送消息提醒
                    //     Util::queuePush('zyhs_question_answer_add_question_reply_notify_check', ['add_question_id' => $addQuestionId, 'astr_id' => $questionInfo['astr_id']], 3600);
                    // }
                    // 追问回复超时 检测
                    Util::queuePush('zyhs_question_answer_add_question_reply_timeout_check', ['add_question_id' => $addQuestionId], Util::getZyhsToAnswerTime($this->request->time()));
                    break;
                case 3://问答
                    $questionGoods = config('zyhs_question');
                    $data = [
                        'uid' => $this->user['id'],
                        'question' => $questionInfo['question'], // 咨询问题
                        'question_type' => $questionInfo['question_type'], // 1=>星盘 2=>骰子 3=>塔罗
                        'gid' => $param['gid'],   // 商品ID
                        'question_extend' => $questionInfo['question_extend'] ?? '',  // 星盘悬赏的档案信息|塔罗结果|骰子结果
                        'is_synastry' => $questionInfo['is_synastry'] ?? 0,   // 是否是合盘
                        'order_num' => $param['out_trade_no'],    // 订单编号
                        'consult_num' => $questionGoods['info'][$param['gid']]['consult_num'],  // 咨询人数
                        'good_amount' => $goods['now_prize'],   // 实际支付价格（准币）
                    ];
                    $qid = $questionModel->SaveData($this->user['id'], $data);
                    if ($qid)
                    {   // 提问成功     发送 接单队列
                        Util::queuePush('zyhs_question_answer_astr_receiving_check', ['qid' => $qid,], 28800);
                    }
                    break;
            }
        }
        catch (\Exception $e)
        {
            Log::write('下单支付异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }
}
